package com.example.sellqq.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.sellqq.constant.ResourceConstant;
import com.example.sellqq.domain.Group;
import com.example.sellqq.util.FileUtils;
import com.example.sellqq.vo.ResponseVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 * @Author: thekernel
 * @Date: 2020/4/20 11:12
 * @Version: 1.0
 * @Description: 蹲号群 Controller
 */
@Api(value = "蹲号群Controller")
@RestController
@RequestMapping("group")
public class GroupController {

    @ApiIgnore
    @GetMapping("hello")
    public @ResponseBody
    String index() {
        return "Hello Group !!!";
    }

    @ApiOperation(value = "获取蹲号群信息", notes = "蹲号群信息")
    @GetMapping("/")
    public @ResponseBody
    ResponseVO getGroup() {
        JSONObject returnData = (JSONObject) JSONObject.parse(FileUtils.getGroup());
        return ResponseVO.success("读取蹲号群成功", returnData);
    }

    @ApiOperation(value = "修改蹲号群信息", notes = "蹲号群信息")
    @PutMapping("/")
    public @ResponseBody
    ResponseVO updateGroup(@RequestBody Group group) {
        JSONObject returnData = (JSONObject) JSONObject.parse(FileUtils.getGroup());
        if (group.getFirst() != null) {
            if (returnData.containsKey("first")) {
                returnData.replace("first", group.getFirst());
            } else {
                returnData.put("first", group.getFirst());
            }
        }
        if (group.getSecond() != null) {
            if (returnData.containsKey("second")) {
                returnData.replace("second", group.getSecond());
            } else {
                returnData.put("second", group.getSecond());
            }
        }

        try {
            File file = new File(ResourceConstant.ABSOLUTE_GROUP_FILE_PATH);
            FileWriter fileWriter = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fileWriter);
            bw.write(returnData.toString());
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseVO.error("修改失败");
        }

        return ResponseVO.success("修改蹲号群信息成功", returnData);
    }

}
